<template>
  <n-card :title="result.fault_type" class="fault-card">
    <n-descriptions bordered column="2" label-placement="left" size="small">
      <n-descriptions-item label="故障线路">
        {{ result.line_name || '未知' }}
      </n-descriptions-item>
      <n-descriptions-item label="故障起始时间">
        {{ result.details.fault_start_time || '未知' }}
      </n-descriptions-item>
      <n-descriptions-item label="设备类型">
        {{ result.details.device_type || '未知' }}
      </n-descriptions-item>
      <n-descriptions-item label="检测到故障">
        <n-tag type="error" v-if="result.fault_detected">是</n-tag>
        <n-tag type="success" v-else>否</n-tag>
      </n-descriptions-item>
      <n-descriptions-item label="候选故障相">
        {{ result.details.candidate_phases?.join(', ') || '无' }}
      </n-descriptions-item>
      <n-descriptions-item label="故障类型">
        {{ result.fault_type || '未知' }}
      </n-descriptions-item>
    </n-descriptions>

    <n-divider />

    <h4>相量图</h4>
    <div class="vector-chart" ref="chartRef"></div>

    <n-divider />

    <h4>电流 RMS 值</h4>
    <n-table :bordered="true" single-line size="small">
      <thead>
        <tr>
          <th>时段</th>
          <th
            v-for="(i, k) in result.details.RMS?.[Object.keys(result.details.RMS || {})[0]]"
            :key="k"
          >
            {{ k.toString().slice(k.toString().length - 2, k.toString().length) }}
          </th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, key) in result.details.RMS" :key="key">
          <td>{{ key }}</td>
          <td v-for="(i, k) in item" :key="key">{{ i }}</td>
        </tr>
      </tbody>
    </n-table>
  </n-card>
</template>

<script setup>
import { ref, onMounted, watch, onBeforeUnmount, nextTick } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  result: { type: Object, required: true },
})

const chartRef = ref(null)
let chart = null

const drawChart = () => {
  if (!chartRef.value) return
  const { phase_angles: angles, phase_magnitudes: mags } = props.result.details
  if (!angles || !mags) return

  const data = Object.keys(angles).map((phase) => ({
    name: phase,
    angle: (450 - angles[phase]) % 360,
    mag: mags[phase],
    color: phase === 'IA' ? '#ff6666' : phase === 'IB' ? '#66cc66' : '#6699ff',
  }))

  if (!chart) chart = echarts.init(chartRef.value)

  const option = {
    title: {
      text: '相量图',
      left: 'center',
      textStyle: { fontSize: 14 },
    },
    polar: {
      radius: '75%',
    },
    angleAxis: {
      type: 'value',
      min: 0,
      max: 360,
      startAngle: 90,
      clockwise: true,
      axisLabel: { formatter: (v) => `${v}°` },
    },
    radiusAxis: {
      min: 0,
      max: Math.max(...data.map((d) => d.mag)) * 1.2,
    },
    tooltip: {
      formatter: (p) => {
        const d = data[p.seriesIndex]
        return `${d.name}<br/>幅值: ${d.mag}<br/>角度: ${angles[d.name]}°`
      },
    },
    series: data.map((d) => ({
      coordinateSystem: 'polar',
      type: 'line',
      name: d.name,
      data: [
        [d.angle, 0],
        [d.angle, d.mag],
      ],
      encode: {
        angle: 0,
        radius: 1,
      },
      lineStyle: {
        color: d.color,
        width: 3,
      },
      symbol: ['none', 'pin'],
      symbolSize: 4,
    })),
    legend: {
      data: data.map((d) => d.name),
      bottom: 0,
    },
  }

  chart.setOption(option)
}

onMounted(async () => {
  await nextTick()
  // 延迟一点等待 Naive UI 完成渲染
  setTimeout(drawChart, 200)
  window.addEventListener('resize', resizeChart)
})

watch(
  () => props.result,
  () => {
    // 等待 DOM 渲染完成后再绘制
    setTimeout(drawChart, 200)
  },
  { deep: true },
)

const resizeChart = () => {
  if (chart) chart.resize()
}

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  if (chart) chart.dispose()
})
</script>

<style scoped>
.vector-chart {
  width: 100%;
  min-height: 200px;
}

.fault-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
